// index.js
//   "tabBar": { "list": [{"text": "首页", "pagePath": "pages/index/index"},{"text": "我的", "pagePath": "pages/mine/mine"} ] },

const app = getApp();
const { envList } = require('../../envList.js');
const esprima = require('../../esprima.js');

Page({
  data: {
    showUploadTip: false,
    powerList: [
      {
        title: '云函数',
        tip: '安全、免鉴权运行业务代码',
        showItem: false,
        item: [
          { title: '获取OpenId',page: 'getOpenId'},
          { title: '生成小程序码', page: 'getMiniProgramCode'}
        ]
      }, 
      {
        title: '数据库',
        tip: '安全稳定的文档型数据库',
        showItem: false,
        item: [
          { title: '创建集合', page: 'createCollection' },
          { title: '更新记录', page: 'updateRecord'}, 
          { title: '查询记录', page: 'selectRecord'}, 
          { title: '聚合操作', page: 'sumRecord'}
        ]
    }, 
    {
      title: '云存储',
      tip: '自带CDN加速文件存储',
      showItem: false,
      item: [{ title: '上传文件', page: 'uploadFile' }]
    }, 
    {
      title: '云托管',
      tip: '不限语言的全托管容器服务',
      showItem: false,
      item: [{ title: '部署服务', page: 'deployService' }]
    }],
    envList,
    selectedEnv: envList[0],
    haveCreateCollection: false,
    bgTextStyle: 'dark',
    scrollTop: '200rpx',
    bgColor: '#ff0000',
    bgColorTop: '#00ff00',
    bgColorBottom: '#0000ff',
    nbTitle: '首页',
    nbLoading: false,
    nbFrontColor: '#000000',
    nbBackgroundColor: '#ffffff',
    pageStyle: "color:#333333",
    background: [
      {img: ""},
      {img: ""}
    ],
    indicatorDots: false,
    vertical: false,
    autoplay: true,
    interval: 2000,
    duration: 500,
    company: "北京融乐物业管理有限公司",
    cloudStorage: "cloud://cloud1-7gm0ghzq62422e29.636c-cloud1-7gm0ghzq62422e29-1308914535/",
    grid: [
      {id:0,path:'', title: "", icon: ""},
      {id:0,path:'', title: "", icon: ""},
      {id:0,path:'', title: "", icon: ""},
      //{id:1,path:'/pages/contact/contact', title: "contact", icon: ""},
      {id:1,path:'', title: "", icon: ""},
      {id:0,path:'', title: "", icon: ""},
      {id:0,path:'', title: "", icon: ""},
      {id:0,path:'', title: "", icon: ""},
      {id:0,path:'', title: "", icon: ""},
      {id:0,path:'', title: "", icon: ""}
    ],
    navs:[
      {title: "首页",class:"co", path:"/pages/index/index", icon: "", font: "fa fa-home"},
      {title: "社区",class:"", path:"", icon: "", font: "fa fa-comments-o"},
      // {title: "维修",class:"", path:"", icon: "", font: "fa fa-wrench"},
      {title: "我的",class:"", path:"/pages/mine/mine", icon: "", font: "fa fa-user-circle"},
    ],
    binds:[],
    notice: {title:''},
    ready: false
  },
  onShow(){
    let v = this;
    if(!v.data.ready) {
      // v.doLogin();
      v.getSwiper();
      // v.getText();
      v.getMenu();
      v.getNotice();
    }
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },
  doLogin(cb){
    let v = this;
    let url = app.globalData.host + '/api/weixin/login';
    if(v.data.ready) return;
    wx.login({
      success (res) {
        v.setData({ready: true});
        if (res.code) {
          wx.request({ url: url, data: { code: res.code },success (res){
            let r = res.data;
            if(r.code == 200 && r.data) {
              
            } else {
              wx.showToast({ title: r.msg, icon: 'none' })
            }
          } })
        } else {
          wx.showToast({ title: res.errMsg, icon: 'none' })
        }
      }
    })
  },
  getSwiper() {
    let v = this;
    let url = app.globalData.host + '/api/common/banner';
    wx.request({
      url: url,
      data: { x: 'x'},
      success (res) {
        // console.log(res.data);
        let r = res.data;
        if(r.code == 200 && r.data) {
          let l = r.data;
          let a = [];
          for(let i in l) {
            let it = {}; Object.assign(it, l[i]);
            a.push(it)
          }
          v.setData({background: a});
          console.log("background",a);
        }
      }
    })
  },
  getNotice(){
    let v = this;
    let url = app.globalData.host + '/api/notice/first';
    let token = app.globalData.token;
    if(!token) {
      app.afterLogin(v,v.getNotice);
      return;
    }
    wx.request({ url: url,data: {token: token}, success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          console.log("getNotice",r.data);
          v.setData({notice: r.data});
        }
      }
    })
  },
  getMenu(){
    let v = this;
    let url = app.globalData.host + '/api/common/menu';
    wx.request({ url: url,success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          let l = r.data;
          let a = v.data.grid;
          let n = 0;
          for(let k in l) {
            if(l[k] && !a[k].path) {
              n++;
              a[k].title = l[k].name;
              a[k].id    = l[k].menu_id;
              a[k].icon  = l[k].icon || a[k].icon;
              a[k].path  = l[k].path || a[k].path;
            } else {
              // a.push(l[k]);
            }
          }
          let host = app.globalData.host;
          if (n < 4 && (host.indexOf('cqtp') > -1)) {
            a[3].title = '乐巢公寓';
            a[3].path = '/pages/rent/rent';
          }
          v.setData({grid: a});
          v.getMyBinds();
          console.log("menu",n,a);
        }
      }
    })
  },
  getMyBinds: function() {
    let v = this;
    let token = app.globalData.token;
    if(!token) {
      app.afterLogin(v,v.getMyBinds);
      return;
    }
    let url = app.globalData.host + '/api/user/owner_list';
    wx.request({
      url: url, data: {token: app.globalData.token},
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          let l = r.data.list || [];
          console.log("getMyBinds",l);
          v.setData({binds: l});
        }
      }
    })
  },
  navigateTo(ev){
    let v = this;
    let dataset = ev.target.dataset;
    let idx = dataset.idx || 0;
    console.log('navigateTo',idx, ev);
    let binds = v.data.binds.length;
    if( (v.data.binds.length == 0) && idx < 3) {
      var msg = '您还没有完成信息绑定，请先绑定住房信息.' + idx + '-' + binds;
      msg = '您还没有完成信息绑定，请先绑定住房信息.';
      wx.showModal({
        title: '提示',
        content: msg,
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定');
            wx.navigateTo({ url: "/pages/binds/binds"});
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return;
    }
    let ds = ev.currentTarget.dataset;
    let ll = v.data.grid;
    
    if(ds && ll[ds.idx]) {
      let lk = ll[ds.idx];
      let path = '/';
      if(lk){
        wx.setStorageSync('menu', lk)
        let menu_id = lk.id;
        // if(menu_id == 1) wx.navigateTo({ url: '/pages/orderPay/pay?menu_id=' + menu_id});
        if(lk.path) {
          path = lk.path + '?menu_id=' + menu_id;
          console.log("idx",ds.idx,path);
          wx.navigateTo({ url: path});
        }
      }
      // console.log('navigateTo',path, lk);
    }
  },
  navToNotice(){
    let v = this;
    let notice = v.data.notice;
    console.log('navToNotice',v.data.notice);
    //notice_id
    wx.navigateTo({ url: '/pages/broadcast/broadcast?notice_id='+v.data.notice.notice_id});
  },
  navTap(ev){
    let v = this;
    let ds = ev.currentTarget.dataset;
    let ll = v.data.navs;
    if(ds && ll[ds.idx]) {
      let lk = ll[ds.idx];
      let path = '/';
      if(lk){
        if(lk.path) {
          path = lk.path ;
          wx.reLaunch({ url: path});
        } else {
          wx.showToast({ title: '敬请期待', icon: 'none' })
        }
      }
      console.log('navTap',path, lk);
    }
  },
  onClickPowerInfo(e) {
    const index = e.currentTarget.dataset.index;
    const powerList = this.data.powerList;
    powerList[index].showItem = !powerList[index].showItem;
    if (powerList[index].title === '数据库' && !this.data.haveCreateCollection) {
      this.onClickDatabase(powerList);
    } else {
      this.setData({
        powerList
      });
    }
  },

  onChangeShowEnvChoose() {
    wx.showActionSheet({
      itemList: this.data.envList.map(i => i.alias),
      success: (res) => {
        this.onChangeSelectedEnv(res.tapIndex);
      },
      fail (res) {
        console.log(res.errMsg);
      }
    });
  },

  onChangeSelectedEnv(index) {
    if (this.data.selectedEnv.envId === this.data.envList[index].envId) {
      return;
    }
    const powerList = this.data.powerList;
    powerList.forEach(i => {
      i.showItem = false;
    });
    this.setData({
      selectedEnv: this.data.envList[index],
      powerList,
      haveCreateCollection: false
    });
  },

  jumpPage(e) {
    wx.navigateTo({
      url: `/pages/${e.currentTarget.dataset.page}/index?envId=${this.data.selectedEnv.envId}`,
    });
  },

  onClickDatabase(powerList) {
    wx.showLoading({
      title: '',
    });
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      config: {
        env: this.data.selectedEnv.envId
      },
      data: {
        type: 'createCollection'
      }
    }).then((resp) => {
      if (resp.result.success) {
        this.setData({
          haveCreateCollection: true
        });
      }
      this.setData({
        powerList
      });
      wx.hideLoading();
    }).catch((e) => {
      console.log(e);
      this.setData({
        showUploadTip: true
      });
      wx.hideLoading();
    });
  }
});
